import {
  authorize,
  showToast,
  router,
  fetchDeviceFileSign,
  fetchDeviceFileUploadState,
  fetchBigPublicFileUploadState,
  showLoading,
  hideLoading,
} from '@ray-js/ray';

import { chooseCropImage, uploadImage, uploadMedia } from './file';

import Strings from '@/i18n';

export const authorizeCamera = () => {
  return new Promise((resolve, reject) => {
    authorize({
      scope: 'scope.camera',
      success: () => {
        resolve(true);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

export const authorizeAlbum = () => {
  return new Promise((resolve, reject) => {
    authorize({
      scope: 'scope.writePhotosAlbum',
      success: () => {
        resolve(true);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

export const handleAvatar = async () => {
  await Promise.all([authorizeCamera(), authorizeAlbum()]);

  const path = await chooseCropImage();
  showLoading({
    title: Strings.getLang('uploading'),
    mask: true,
  });
  try {
    const res = await uploadMedia('image', path, 'pet');
    const { cloudKey, publicUrl } = res;
    return { cloudKey, publicUrl, path };
  } catch (error) {
    console.log('error:', error);
  } finally {
    hideLoading();
  }
};
